package app.qrcode.browser.todoapp.fragments.update

import android.app.AlertDialog
import android.view.*
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import app.qrcode.browser.todoapp.R
import app.qrcode.browser.todoapp.common.ViewBindingFragment
import app.qrcode.browser.todoapp.data.models.ToDoData
import app.qrcode.browser.todoapp.data.viewmodel.ToDoViewModel
import app.qrcode.browser.todoapp.databinding.FragmentUpdateBinding
import app.qrcode.browser.todoapp.fragments.SharedViewModel

class UpdateFragment : ViewBindingFragment<FragmentUpdateBinding>(), DatePickerFragment.DateChosen,
    TimePickerFragment.TimeChosen {

    private val mSharedViewModel: SharedViewModel by activityViewModels()

    private val mToDoViewModel: ToDoViewModel by activityViewModels()


    override fun initView() {
        super.initView()
        setHasOptionsMenu(true)
        val itemData = arguments?.get("item") as ToDoData
        binding.currentTitleEt.setText(itemData.title)
        binding.currentDescriptionEt.setText(itemData.descriptor)
        binding.currentSetDateTv.text = if (itemData.date != null) itemData.date else "Set Date"
        binding.currentSetTimeTv.text = if (itemData.time != null) itemData.time else "Set Time"
        binding.currentSwitch.isChecked = itemData.isNoticed
        binding.currentPrioritiesSpinner.apply {
            setSelection(mSharedViewModel.parsePriority(itemData.priority))
            onItemSelectedListener = mSharedViewModel.listener
        }
        binding.currentTaskStatusSpinner.apply {
            setSelection(mSharedViewModel.parseTaskStatus(itemData.taskStatus))
            onItemSelectedListener = mSharedViewModel.listener
        }
        binding.currentSetDateTv.setOnClickListener {
            var datePickerFragment = DatePickerFragment()
            datePickerFragment.run {
                setDateChosen(this@UpdateFragment)
                show(this@UpdateFragment.parentFragmentManager, "datePicker")
            }


        }
        binding.currentSetTimeTv.setOnClickListener {
            var timePickerFragment = TimePickerFragment()
            timePickerFragment.run {
                setTimeChosen(this@UpdateFragment)
                show(this@UpdateFragment.parentFragmentManager, "timePicker")
            }
        }
//        binding.startServiceBtn.setOnClickListener {
//            val intent = Intent(this@UpdateFragment.requireActivity(), MyService::class.java)
//            this.requireActivity().startService(intent)
//
//        }
//
//        binding.endServiceBtn.setOnClickListener {
//
//        }
//        mToDoViewModel.currentDate.observe(this) {
//            it?.let { binding.currentSetDateTv.text = it }
//        }
//        mToDoViewModel.currentTime.observe(this) {
//            it?.let { binding.currentSetTimeTv.text = it }
//        }
    }

//    override fun onCreateView(
//        inflater: LayoutInflater, container: ViewGroup?,
//        savedInstanceState: Bundle?
//    ): View? {
//        // Inflate the layout for this fragment
//
//        return inflater.inflate(R.layout.fragment_update, container, false)
//    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.update_fragment_menu, menu)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_save -> updateItem()
            R.id.menu_delete -> confirmItemRemoval()
        }
        return super.onOptionsItemSelected(item)
    }


    private fun updateItem() {
        val title = binding.currentTitleEt.text.toString()
        val description = binding.currentDescriptionEt.text.toString()
        val getPriority = binding.currentPrioritiesSpinner.selectedItem.toString()
        val getTaskStatus = binding.currentTaskStatusSpinner.selectedItem.toString()
        val mDate =
            if (binding.currentSetDateTv.text.toString() != "Set Date") binding.currentSetDateTv.text.toString() else null
        val mTime =
            if (binding.currentSetTimeTv.text.toString() != "Set Time") binding.currentSetTimeTv.text.toString() else null
        val isNoticed = binding.currentSwitch.isChecked
        val validation = mSharedViewModel.verifyDataFromUser(title, description)
        if (validation) {
            val itemData = arguments?.get("item") as ToDoData
            val updatedItem =
                ToDoData(
                    itemData.id,
                    title,
                    mSharedViewModel.parsePriority(getPriority),
                    mSharedViewModel.parseTaskStatus(getTaskStatus),
                    description,
                    date = mDate,
                    time = mTime,
                    isNoticed = isNoticed
                )
            mToDoViewModel.updateData(updatedItem)
            Toast.makeText(requireContext(), "Successfully Update!", Toast.LENGTH_SHORT).show()
            findNavController().navigate(R.id.action_updateFragment_to_listFragment)
        } else {
            Toast.makeText(requireContext(), "Please fill out all field", Toast.LENGTH_SHORT).show()
        }
    }

    private fun confirmItemRemoval() {
        val itemData = arguments?.get("item") as ToDoData
        val builder = AlertDialog.Builder(requireContext())
        builder.setPositiveButton("Yes") { _, _ ->
            mToDoViewModel.deleteItem(itemData)
            Toast.makeText(
                requireContext(),
                "Successfully Removed:'${itemData.title}'",
                Toast.LENGTH_SHORT
            ).show()
            findNavController().navigate(R.id.action_updateFragment_to_listFragment)
        }
        builder.setNegativeButton("No") { _, _ -> }
        builder.setTitle("Delete ${itemData.title} ?")
        builder.setMessage("Are you sure you want to remove '${itemData.title}'")
        builder.create().show()
    }

    override fun setDate(str: String) {
//        mToDoViewModel.currentDate.value = str
//        Log.w("gyk", "UpdateFragment.setDate -> $str")
        binding.currentSetDateTv.text = str
    }

    override fun setTime(str: String) {
        binding.currentSetTimeTv.text = str
//        mToDoViewModel.currentTime.value = str
//        Log.w("gyk", "UpdateFragment.setTime -> $str")
    }


}